package cn.infrabase.core.util;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.Nullable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;

/**
 * 字符集工具类。
 *
 * @author Weimin Gao
 * @since 1.0.0
 **/
@Slf4j
public class CharsetUtils {

    /**
     * ISO-8859-1
     */
    public static final String ISO_8859_1 = "ISO-8859-1";

    /**
     * UTF-8
     */
    public static final String UTF_8 = "UTF-8";

    /**
     * GBK
     */
    public static final String GBK = "GBK";

    /**
     * ISO-8859-1
     */
    public static final Charset CHARSET_ISO_8859_1 = StandardCharsets.ISO_8859_1;

    /**
     * UTF-8
     */
    public static final Charset CHARSET_UTF_8 = StandardCharsets.UTF_8;

    /**
     * GBK
     */
    public static final Charset CHARSET_GBK;

    static {
        Charset charset = null;
        try {
            charset = Charset.forName(GBK);
        } catch (UnsupportedCharsetException e) {
            log.error("字符集【GBK】不支持");
        }
        CHARSET_GBK = charset;
    }

    /**
     * 返回给定的字符集。
     *
     * @param charset 给定的字符集，为空时则返回UTF-8编码字符集。
     * @return 字符集对象。
     * @throws CharsetNotSupportException 如果给定的字符集系统不支持时。
     * @see Charset
     */
    public static Charset charset(@Nullable String charset) throws CharsetNotSupportException {
        try {
            return StringUtils.isBlank(charset) ? CHARSET_UTF_8 : Charset.forName(charset);
        } catch (UnsupportedCharsetException e) {
            throw new CharsetNotSupportException(charset);
        }
    }

}
